<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="document">
        <el-input v-model="queryParams.document" placeholder="请输入单据编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['allot:allot:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['allot:allot:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="allotList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据编号" align="center" prop="document" />
      <el-table-column label="原仓库" align="center" prop="primaryWarehouse" />
      <el-table-column label="调拨仓库" align="center" prop="allotWarehouse" />
      <el-table-column label="审批状态" align="center" prop="approveState">
        <template #default="scope">
          <dict-tag :options="approve_state" :value="scope.row.approveState" />
        </template>
      </el-table-column>
      <el-table-column label="调拨状态" align="center" prop="allotState">
        <template #default="scope">
          <dict-tag :options="allot_state" :value="scope.row.allotState" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.approveState == 0 && scope.row.allotState == 0"
            :disabled="scope.row.num == 0" @click='update(scope.row)'>提交申请</el-button>
          <el-button link type="primary" v-if="scope.row.approveState == 0 && scope.row.allotState == 0"
            @click='navigateToAllot(scope.row)'>查看详情</el-button>
          <el-button link type="primary" v-if="scope.row.approveState == 2 && scope.row.allotState == 2"
            @click='Allot(scope.row.document)'>查看记录</el-button>
          <el-button link type="primary" v-if="scope.row.approveState == 1 && scope.row.allotState == 1"
            @click='updateInventoryAllot(scope.row)'>撤销审批</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['allot:allot:remove']"
            v-if="scope.row.approveState == 0 && scope.row.allotState == 0">删除</el-button>
          <el-button link type="primary" v-if="scope.row.approveState == 2 && scope.row.allotState == 1"
            @click='playAllot(scope.row.document)'>进行调拨</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改调拨对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="allotRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="原仓库" prop="primaryWarehouseId">
          <el-select v-model="form.primaryWarehouseId" placeholder="请选择原仓库">
            <el-option v-for="option in data.primaryWarehouseOptions" :key="option.value" :label="option.label"
              :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调拨仓库" prop="allotWarehouseId">
          <el-select v-model="form.allotWarehouseId" placeholder="请选择调拨仓库">
            <el-option v-for="option in data.allotWarehouseOptions" :key="option.value" :label="option.label"
              :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情-->
    <el-dialog :title="title2" v-model="open2" width="1050px" append-to-body>
      <el-table v-loading="orderload" :data="orderList">
        <el-table-column label="商品编号" align="center" prop="goodNo" />
        <el-table-column label="商品" align="center" prop="goodsName" />
        <el-table-column label="原仓库" align="center" prop="primaryLocation" />
        <el-table-column label="调拨位置" align="center" prop="allotLocation" />
        <el-table-column label="调拨时间" align="center" prop="allotDate" />
      </el-table>
      <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm2">关闭</el-button>
      </div>
    </template>
    </el-dialog>
  </div>
</template>

<script setup name="Allot">
import { listAllot, getAllot, delAllot, addAllot, updateAllot } from "@/api/inventory/allot";
import request from "@/utils/request";
import { useRouter, useRoute } from "vue-router";


const router = useRouter();
const route = useRoute;
const { proxy } = getCurrentInstance();
const { allot_state, approve_state } = proxy.useDict('allot_state', 'approve_state');

const allotList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const state = 0
const states = 1
const open2 = ref(false);
const title2 = ref('调拨记录');
const orderList = ref([]);
const orderload = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    document: null,
  },
  rules: {
    document: [
      { required: true, message: "单据编号不能为空", trigger: "blur" }
    ],
    primaryWarehouseId: [
      { required: true, message: "原仓库不能为空", trigger: "blur" }
    ],
    allotWarehouseId: [
      { required: true, message: "调拨仓库不能为空", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value === data.form.primaryWarehouseId) {
            callback(new Error('原仓库和调拨仓库不能相同'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    // 添加以下两个数组
    primaryWarehouseOptions: [],
    allotWarehouseOptions: [],
  },
});

const { queryParams, form, rules } = toRefs(data);


//传输单据编号
const navigateToAllot = (row) => {
  router.push({
    path: '/inventory/allot',
    query: {
      document: row.document,
      primaryWarehouseId: row.primaryWarehouseId,
      allotWarehouseId: row.allotWarehouseId
    }
  });
};

//查看记录
function Allot(documentValue) {
  open2.value = true;
  ck(documentValue)
}

function ck(documentValue) {
  orderload.value = true;
  request({
    url: '/inventory/record/list',
    method: 'get',
    params: {
      document: documentValue
    }
  })
    .then((response) => {
      orderList.value = response.rows;
      total.value = response.total;
      orderload.value = false;
    });
}

//进行调拨
const playAllot = (documentValue) => {
  router.push({
    path: '/inventory/allot',
    query: {
      document: documentValue,
      state,
      states
    }
  });
};


//调用查询仓库名方法加载新增下拉框
function fetchData() {
  loading.value = true;
  return request({
    url: '/warehouseManagement/warehouse/list',
    method: 'get',
  }).then((resp) => {
    // 存储原仓库选项
    data.primaryWarehouseOptions = resp.rows.map(item => ({ value: item.id, label: item.name }));
    // 存储调拨仓库选项（如果两者相同，可以只设置一个数组）
    data.allotWarehouseOptions = resp.rows.map(item => ({ value: item.id, label: item.name }));
    loading.value = false;
    return resp; // 返回响应，以便在调用处处理
  });
}

//撤销审批
function updateInventoryAllot(row) {
  proxy.$modal.confirm('是否撤销提交的审批？').then(function () {
    request({
      url: '/allot/allot/updateStatus',
      method: 'put',
      params: {
        document: row.document,
      }
    });
  }).then(() => {
    getList();
    const data = {
      approveState: 4,
      document: row.document,
    }
    request({
      url: '/inventory/approve',
      method: 'put',
      data: data
    })
    proxy.$modal.msgSuccess("撤销成功");
  }).catch(() => {
    proxy.$modal.msgWarning("撤销取消");
  });
}

//提交审批
function update(row) {
  proxy.$modal.confirm('是否提交的审批？').then(function () {
    request({
      url: '/allot/allot/update',
      method: 'put',
      params: {
        document: row.document,
      }
    });
  }).then(() => {
    getList();
    const data = {
      document: row.document,
      approveState: 1
    }
    request({
      url: '/inventory/approve',
      method: 'post',
      data: data
    })
    proxy.$modal.msgSuccess("提交成功");
  }).catch(() => {
    proxy.$modal.msgWarning("提交取消");
  });
}

/** 查询调拨列表 */
function getList() {
  fetchData()
    .then(() => {
      loading.value = true;
      listAllot(queryParams.value).then(response => {
        allotList.value = response.rows;
        total.value = response.total;
        loading.value = false;
      });
    });
}



// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    document: null,
    approveState: null,
    allotState: null
  };
  proxy.resetForm("allotRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
async function handleAdd() {
  // 调用 fetchData 获取仓库选项并等待其完成
  await fetchData();
  reset();
  open.value = true;
  title.value = "添加调拨";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["allotRef"].validate(valid => {
    if (valid) {
      if (form.value.id !== null) {
        updateAllot(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAllot(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除调拨编号为"' + _ids + '"的数据项？').then(function () {
    return delAllot(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('allot/allot/export', {
    ...queryParams.value
  }, `allot_${new Date().getTime()}.xlsx`)
}

function submitForm2() {
  open2.value = false;
}

getList();
</script>